package com.zbkj.crmeb.order.channel;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import com.zbkj.crmeb.plat.by.dto.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.crmeb.core.common.CommonResult;
import com.utils.RestTemplateUtil;
import com.crmeb.core.config.RestTemplateConfig;
import com.zbkj.crmeb.enums.PurchaseOrderChannelTypeEnum;
import com.zbkj.crmeb.order.AbstractStoreOrderService;
import com.zbkj.crmeb.order.StoreOrderFactory;
import com.zbkj.crmeb.order.request.ViettiOrderRequest;
import com.zbkj.crmeb.order.request.ViettiOrderRequest.Address;
import com.zbkj.crmeb.store.dao.StoreOrderDao;
import com.zbkj.crmeb.store.model.StoreOrder;
import com.zbkj.crmeb.store.model.StoreProductAttrValue;
import com.zbkj.crmeb.store.service.StoreProductAttrValueService;
import com.zbkj.crmeb.store.service.StoreProductService;
import com.zbkj.crmeb.store.vo.StoreOrderInfoVo;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class ViettiStoreOrderServiceImpl extends AbstractStoreOrderService {
    @Autowired
    RestTemplateUtil restTemplateUtil;
    @Resource
    private StoreOrderDao storeOrderDao;
    @Autowired
    RestTemplateConfig restTemplateConfig;
    @Autowired
    StoreProductAttrValueService storeProductAttrValueService;
    @Autowired
    StoreProductService storeProductService;
    @Autowired
    StoreOrderFactory storeOrderFactory;
    
    /********* vietti配置参数  *********/
    @Value("${vietti.client}")
    private String viettiClient;
    @Value("${vietti.appSecret}")
    private String viettiAppSecret;
    @Value("${vietti.appkey}")
    private String viettiAppKey;
    @Value("${vietti.url.domain}")
    private String viettiDomian;
    @Value("${vietti.url.products}")
    private String viettiProducts;
    @Value("${vietti.url.stocks}")
    private String viettiStocks;
    @Value("${vietti.url.order}")
    private String viettiOrderUrl;

    @Override
    public CommonResult<Object> addChannelOrder(StoreOrder storeOrder , List<StoreOrderInfoVo> orderInfoVoList) {
        List<String> errorMessages = new ArrayList<>();
        try {
            orderInfoVoList.stream().forEach(order ->{
                String barCode = order.getInfo().getProductInfo().getBarCode();
                String sourceSkuId = order.getInfo().getProductInfo().getAttrInfo().getSourceSkuId();
                StoreProductAttrValue value = storeProductAttrValueService.getOne(Wrappers.<StoreProductAttrValue>lambdaQuery()
                        .eq(StoreProductAttrValue :: getBarCode, barCode)
                        .eq(StoreProductAttrValue :: getSourceSkuId, sourceSkuId)
                        .last("LIMIT 1")
                        );
                String[] suk = value.getSuk().split(",");
                if(9 != storeOrder.getSource()) {
                    storeOrder.setPushOrderNo(order.getChildOrderNumber());
                }
                // 组建订单对象
                ViettiOrderRequest viettiOrderRequest = new ViettiOrderRequest();
                viettiOrderRequest.setChannelOrderID(storeOrder.getPushOrderNo());
                viettiOrderRequest.setChannelOrderCreated(storeOrder.getCreateTime());
                viettiOrderRequest.setChannelOrderStatus("created");
                viettiOrderRequest.setChannelOrderStatusUpdated(storeOrder.getPayTime());
                viettiOrderRequest.setProductID(barCode.substring(4, barCode.length()));
                viettiOrderRequest.setSize(suk.length > 1 ? suk[1] : suk[0]);
                viettiOrderRequest.setSoldUnits(order.getInfo().getCartNum());
                viettiOrderRequest.setUnitSellingPrice(value.getPrice().divide(new BigDecimal("8"), 2, RoundingMode.HALF_UP));
                viettiOrderRequest.setAdministrativeNotes(storeOrder.getRemark());
                viettiOrderRequest.setTestMode(false);
//                viettiOrderRequest.setBillingAddress(getBillingAddress());
//                viettiOrderRequest.setShippingAddress(getShippingAddress());

                Result result = pushOrder(storeOrder, viettiOrderRequest, order);
                if(!result.isSuccess()){
                    errorMessages.add("订单号: " + order.getOrderInfoId() + ",错误: " + result.getMessage());
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (!errorMessages.isEmpty()) {
            return CommonResult.failed(String.join("\n", errorMessages));
        }
        return CommonResult.success();
    }


    /**
     * 获取buyer商品数据和详情
     * @Description:
     * @author daigb
     * @param @param id 商品barCode
     * @param @return
     * @param @throws Exception
     * @return BuyerProductResDTO
     * @throws
     */
    private Result pushOrder(StoreOrder storeOrder, ViettiOrderRequest request, StoreOrderInfoVo orderInfo) {
//    	String orderId = storeOrder.getSource() == 9 ? storeOrder.getOrderId().split("-")[0] : storeOrder.getOrderId();
        // 组装请求url
        StringBuilder sb = new StringBuilder();
        sb.append(viettiDomian);
        sb.append("/");
        sb.append(viettiClient);
        sb.append(viettiOrderUrl);
        sb.append("?channelKey=");
        sb.append(viettiAppSecret);
        // 发送请求
        RestTemplate restTemplate = restTemplateConfig.restTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.add("Ocp-Apim-Subscription-Key", viettiAppKey);
        HttpEntity<String> formEntity = new HttpEntity<>(JSON.toJSONString(request), headers);
        ResponseEntity<String> response = restTemplate.postForEntity(sb.toString(), formEntity , String.class);

        if (HttpStatus.OK != response.getStatusCode()) {
            JSONObject message = JSONObject.parseObject(response.getBody());
            String errorMessage = message.getString("error");

            log.info("--------------- VIETTI订单{} ---------------", errorMessage);
            return new Result(false, null, errorMessage);
        }
        JSONObject responseData = JSONObject.parseObject(response.getBody()).getJSONObject("data");
        String status = responseData.getString("status");
        if("201".equals(status)) {
            //新增采购单
            storeOrderFactory.insertPurchaseOrder(storeOrder, true, PurchaseOrderChannelTypeEnum.VIETTI.getCode());
            //新增采购商品
            storeOrderFactory.insertPurchaseGoods(orderInfo, storeOrder, true, "成功", null);
            if(storeOrder.getPushStatus() != 2){
        		StoreOrder storeOrderUpdate = new StoreOrder();
        		storeOrderUpdate.setId(storeOrder.getId());
        		storeOrderUpdate.setPushStatus(1);
        		storeOrderUpdate.setPushMessage(responseData.getString("title"));
                storeOrderDao.updateById(storeOrderUpdate);
            }
            log.info("--------------- VIETTI订单推送成功 ---------------");
            return new Result(true);
        } else {
            //新增采购单
        	storeOrderFactory.insertPurchaseOrder(storeOrder, false, PurchaseOrderChannelTypeEnum.VIETTI.getCode());
            //新增采购商品
        	storeOrderFactory.insertPurchaseGoods(orderInfo, storeOrder, false, "失败", null);
    		StoreOrder storeOrderUpdate = new StoreOrder();
    		storeOrderUpdate.setId(storeOrder.getId());
    		storeOrderUpdate.setPushStatus(2);
    		storeOrderUpdate.setPushMessage(responseData.getString("title"));
            storeOrderDao.updateById(storeOrderUpdate);
            log.info("--------------- VIETTI订单推送失败 ---------------");
            return new Result(false, null, responseData.getString("title"));
        }
    
    }

    /**
     * 构建商户信息
     * @Description:  
     * @author daigb 
     * @param @return
     * @return Address
     * @throws
     */
    private Address getBillingAddress() {
        Address billingAddress = new Address();
        billingAddress.setBusinessName("La vita srl");
        billingAddress.setSurname("La vita srl");
        billingAddress.setEmail("caigou@wzcprs.com");
        billingAddress.setStreetName("via emanuele filiberto 257,00185 roma");
        billingAddress.setStreetNumber("257");
        billingAddress.setCity("roma");
        billingAddress.setState("roma");
        billingAddress.setCountry("IT");
        billingAddress.setPhone("+393898858155");
        billingAddress.setMobile("+393898858155");
        billingAddress.setVatNumber("13691531001");
        billingAddress.setVatNumber("13691531001");
        
        return billingAddress;
    }
    
    /**
     * 构建税收信息
     * @Description:  
     * @author daigb 
     * @param @return
     * @return Address
     * @throws
     */
    private Address getShippingAddress() {
        Address shippingAddress = new Address();
        shippingAddress.setBusinessName("Grace");
        shippingAddress.setSurname("Grace");
        shippingAddress.setEmail("caigou@wzcprs.com");
        shippingAddress.setStreetName("Block C, 8/F, Success Industrial Building No. 7 Kin Fat Street, Tuen Mun, N.T. H.K");
        shippingAddress.setStreetNumber("8/F");
        shippingAddress.setCity("HongKong");
        shippingAddress.setState("HongKong");
        shippingAddress.setCountry("HK");
        shippingAddress.setPhone("+852 2555 6388");
        shippingAddress.setMobile("+852 2555 6388");
        
        return shippingAddress;
    }

    @Override
    public CommonResult<Object> cancelChannelOrder(StoreOrder storeOrder, List<StoreOrderInfoVo> orderInfoVoList) {
        return null;
    }

    @Override
    public CommonResult<Object> getOrderInfo(String channelOrderSn) {
        return null;
    }

}
